<!doctype html>
<title>DOMParser parse CDATA sections when parsing XML files</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>
"use strict";

function checkMetadata(doc, contentType) {
  assert_true(doc instanceof Document, "Should be Document");
  //  assert_equals(doc.URL, document.URL, "URL");
  //  assert_equals(doc.documentURI, document.URL, "documentURI");
  assert_equals(doc.characterSet, "UTF-8", "characterSet");
  assert_equals(doc.charset, "UTF-8", "charset");
  assert_equals(doc.inputEncoding, "UTF-8", "inputEncoding");
  assert_equals(doc.contentType, contentType, "contentType");
  assert_equals(doc.location, null, "location");
}

const allowedTypes = ["text/xml", "application/xml", "application/xhtml+xml", "image/svg+xml"];

allowedTypes.forEach(type => {
  test(() => {
    const p = new DOMParser();
    const doc = p.parseFromString(`<foo><![CDATA[> < " and &]]></foo>`, type);
    assert_true(doc instanceof Document, "Should be Document");
    checkMetadata(doc, type);
    assert_equals(doc.documentElement.namespaceURI, null);
    assert_equals(doc.documentElement.localName, "foo");
    assert_equals(doc.documentElement.tagName, "foo");

    assert_equals(doc.documentElement.childNodes.length, 1);
    assert_equals(doc.documentElement.childNodes[0].nodeName, "#cdata-section");
    assert_equals(doc.documentElement.childNodes[0].nodeType, 4);

    assert_equals(doc.documentElement.textContent, "> < \" and &");

  }, "Should parse reserved characters within a CDATA section in type " + type);

  test(() => {
    const p = new DOMParser();
    const doc = p.parseFromString(`<foo ID="8">
  <![CDATA[<p class="red"><span class="big">HTML in CDATA.</span></p>]]></foo>`, type);
    assert_true(doc instanceof Document, "Should be Document");
    checkMetadata(doc, type);
    assert_equals(doc.documentElement.namespaceURI, null);
    assert_equals(doc.documentElement.localName, "foo");
    assert_equals(doc.documentElement.tagName, "foo");

    assert_equals(doc.documentElement.childNodes.length, 2);
    assert_equals(doc.documentElement.childNodes[0].nodeName, "#text");
    assert_equals(doc.documentElement.childNodes[0].nodeType, 3);
    assert_equals(doc.documentElement.childNodes[1].nodeName, "#cdata-section");
    assert_equals(doc.documentElement.childNodes[1].nodeType, 4);

    assert_equals(
      doc.documentElement.textContent,
      "\n  <p class=\"red\"><span class=\"big\">HTML in CDATA.</span></p>"
    );

  }, "Should parse HTML within a CDATA section in type " + type);
});
</script>
